import { ElMessage } from 'element-plus'

export const copyUtils = {
  methods: {
    copyClipboardApi (text) {
      // Use the Async Clipboard API when available. Requires a secure browsing
      // context (i.e. HTTPS)
      if (!navigator.clipboard) {
        throw this.makeError()
      }
      return navigator.clipboard.writeText(text)
    },
    makeError () {
      return new DOMException('The request is not allowed', 'NotAllowedError')
    },
    copyExecCommand (text) {
      // Put the text to copy into a <span>
      const span = document.createElement('span')
      span.textContent = text
    
      // Preserve consecutive spaces and newlines
      span.style.whiteSpace = 'pre'
      span.style.webkitUserSelect = 'auto'
      span.style.userSelect = 'all'
    
      // Add the <span> to the page
      document.body.appendChild(span)
    
      // Make a selection object representing the range of text selected by the user
      const selection = window.getSelection()
      const range = window.document.createRange()
      selection.removeAllRanges()
      range.selectNode(span)
      selection.addRange(range)
    
      // Copy text to the clipboard
      let success = false
      try {
        success = window.document.execCommand('copy')
      } finally {
        // Cleanup
        selection.removeAllRanges()
        window.document.body.removeChild(span)
      }
    
      if (!success) throw this.makeError()
    },
    async clipboardCopy (text) {
      let isSuccess = false
      try {
        isSuccess = await this.copyClipboardApi(text)
      } catch (err) {
        try {
          isSuccess = await this.copyExecCommand(text)
        } catch (err2) {
          throw (err2 || err || this.makeError())
        }
      }
      if(isSuccess) {
        if(textCompObj.hint){
          this.showToast(textCompObj.hint)
        }else{
          this.showToast("复制失败！")
        }
      } else {
        this.showToast("复制成功！")
      }
    },
    showToast(msg) {
      //load事件不提示错误信息
      if(msg) {
        ElMessage(msg);
      }
    },
  }
}

